/**
 * A very simple product editor
 */
'use strict';
var Product = require('../../../models/productModel');

module.exports = function (router) {

    /**
     * Retrieve a list of all products for editing.
     */
    router.get('/', function (req, res) {

	Product.find(function (err, prods) {
	    if (err) {
		console.log(err);
	    }
	    prods.forEach(function(prod) {
		prod.prettyPrice = prod.prettyPrice();
	    });
	    var model =
		    {
			products: prods
		    };
	    res.render('admin/products', model);              // 'products' 是dust的模块文件
	});

    });


    /**
     * Add a new product to the database.
     * **** PLEASE READ THE COMMENT BELOW! ****
     */
    router.post('/', function (req, res) {

        var item_id = req.body.item_id,
	    name = req.body.name && req.body.name.trim(),
            brand = req.body.brand,
            place = req.body.place,
            qty = req.body.qty,
            packing = req.body.packing,
            spec = req.body.spec,
            tag = req.body.tag,
            keyword = req.body.keyword,
            taobao_url = req.body.taobao_url,
            intro = req.body.intro;

	var price = parseFloat(req.body.price, 10);


	//Some very lightweight input checking
	if (name === '' || isNaN(price)) {
	    res.redirect('/admin/products#BadInput');
	    return;
	}

	var newProduct = new Product({
            item_id: item_id,
            name: name,
            brand: brand,
            price: price,
            place: place,
            qty: qty,
            packing: packing,
            spec: spec,
            tag: tag,
            keyword: keyword,
            taobao_url: taobao_url,
            intro: intro
        });

	//Show it in console for educational purposes...
	newProduct.whatAmI();
	/* The call back recieves to more arguments ->product/s that is/are added to the database
	 and number of rows that are affected because of save, which right now are ignored
	 only errors object is consumed*/
	newProduct.save(function(err) {
	    if(err) {
		console.log('save error', err);
	    }

	    res.redirect('/admin/products');
	});
    });

    /**
     * Delete a product.
     * @paaram: req.body.item_id Is the unique id of the product to remove.
     */
    router.delete('/', function (req, res) {
	Product.remove({_id: req.body.item_id}, function (err) {
	    if (err) {
		console.log('Remove error: ', err);
	    }
	    res.redirect('/admin/products');
	});
    });


    /**
     * Edit a product.
     * Not implemented here
     */
    router.put('/', function (req, res) {
	console.log('PUT received. Ignoring.');
	res.redirect('/admin/products');
    });

};
